var express = require('express');
var router = express.Router();
const {uploadFile} = require("../utils/upload");
const {create,get,update,remove,createServe,getServe,updateServe,removeServe} = require('../servies/storeService')

/* GET users listing. */
router.get('/', async function (req, res, next) {
    let {page,limit,sort,type,title} = req.query;
    let data = {};
    if (!type) {
        data = {}
    }else {
        data = {[type]:title}
    }
    const result = await get({page,limit,sort,data});
    res.send(result);
});
router.post('/create', async function (req, res, next) {
    const data = req.body;
    data.count=0;
    data.CreationTime=new Date();
    const result = await create(data);
    res.send(result);
});

router.post('/update', async function (req, res, next) {
    const data = req.body;

    const result = await update(data);
    res.send(result);
});
router.post('/delete', async function (req, res, next) {
    const {_id} = req.body;

    const result = await remove(_id);
    res.send(result);
});


//服务
router.post('/createServe', async function (req, res, next) {
    const data = req.body;
    data.count=0;
    data.CreationTime=new Date();
    const result = await createServe(data);
    res.send(result);
});
router.get('/Serve', async function (req, res, next) {
    let {page,limit,sort,type,title} = req.query;
    let data = {};
    if (!type) {
        data = {}
    }else {
        data = {[type]:title}
    }
    const result = await getServe({page,limit,sort,data});
    res.send(result);
});

router.post('/updateServe', async function (req, res, next) {
    const data = req.body;

    const result = await updateServe(data);
    res.send(result);
});
router.post('/deleteServe', async function (req, res, next) {
    const {_id} = req.body;

    const result = await removeServe(_id);
    res.send(result);
});

router.post('/goodsUpload/:_id', async function(req, res, next) {
    const {_id} = req.params;
    const {data,success} = await uploadFile(req,{
        fileType:"goodsImgs",
        path:"./public/imgs/goods"
    })
    if (success) {
        const params = {$push:{imgs:data.url}}
        const result = await update({_id,...params});
        //  await getById(data._id);
        res.send(result);
        return;
    }
});

module.exports = router;